package com.taiyuan.zfmvp.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.taiyuan.zfmvp.utils.Base64Util;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @param
 * @Author: zhoufang@sxjtjt.net
 * @Descriiption:
 * @Date 2023/9/7
 * @return
 */
public class testMain2 {
    public static void main(String[] args) throws Exception {



        tokenVo to = new tokenVo();
        to.setClientId("4111ea97dffa163e9d2a183dea15fweb");
        to.setClientSecret("f11ffb5c041b11ea97dffa163e9d2a29");
        to.setUserName("18211111111");
        to.setUpass(Base64Util.encryptBASE64("abcd1234".getBytes()));
        to.setSignData("RGXxfLvatMfoyFzqHOAw3Pn4rrJS9+pzczfnlAFGlF7GEx8ZqK2PZp716Td7ZC0Zi06eAnfS5DtyUc1bESapy062Gcoed3pD0o0oeo9er+T+98io2dBkjOpKekIuNXYsibMhnmvw3WTdhvbOlbY1lCVbVLayyy0atLcl8tXsoWo=");
        to.setTime(currentTime());
        to.setBranchCode("49adb23841da3214518shanxijiantou");

        String url = "http://220.194.138.143:60080/ntocc-tms-api/openApi/getToken";
        System.out.println("token请求地址："+ url);
        System.out.println("token请求参数："+ JSON.toJSONString(to));
        String result = null;
        try {
            result = HttpUtil.post(url, JSON.toJSONString(to));
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        System.out.println("token请求回参："+ result);
        JSONObject resultJson = JSONObject.parseObject(result);
        String token = resultJson.getString("data");
        System.out.println(token);

        //二次加密token
        String newToken = getToken(token);
        System.out.println(newToken);
        String geturl = "http://220.194.138.143:60080/ntocc-tms-api/openApi/driverList";

        String getParam = "driverType=1&pageNum=1&pageSize=20&total=50&branchCodeExt=49adb23841da3214518shanxijiantou&phone=13696858842&vehicleLicenseNumber=陕AX5062";
        String getResult = sendGet2(geturl+"?"+getParam,newToken);
        System.out.println("司机列表接口回参："+getResult);
        JSONObject driverJson = JSONObject.parseObject(getResult);
        JSONObject data = driverJson.getJSONObject("data");
        int total = (Integer)data.get("total");
        System.out.println("查询到数据条数"+total);
        JSONArray array = data.getJSONArray("records");
        String partyCode =  array.getJSONObject(0).getString("partyCode");
        System.out.println("partyCode:"+partyCode);

    }

    public static String sendGet2(String url, String token)
    {
        CloseableHttpClient httpCilent2 = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(300 * 1000)   //设置连接超时时间
                .setConnectionRequestTimeout(300 * 1000) // 设置请求超时时间
                .setSocketTimeout(300 * 1000)
                .setRedirectsEnabled(true)//默认允许自动重定向
                .build();
        HttpGet httpGet2 = new HttpGet(url);
        httpGet2.setConfig(requestConfig);
        httpGet2.setHeader("Authorization", "Bearer "+token);
        httpGet2.setHeader("deviceId", "0000000000");
        String srtResult = "";
        try {
            HttpResponse httpResponse = httpCilent2.execute(httpGet2);
            if(httpResponse.getStatusLine().getStatusCode() == 200){
                srtResult = EntityUtils.toString(httpResponse.getEntity());//获得返回的结果

            }else if(httpResponse.getStatusLine().getStatusCode() == 400){
                //..........
            }else if(httpResponse.getStatusLine().getStatusCode() == 500){
                //.............
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                httpCilent2.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return srtResult;
    }

    public static String currentTime() {
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
        return sf.format(new Date());
    }

    public static String currentTimefahuo() {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sf.format(new Date());
    }




    public static String getToken(String token) {
        long floor = new Date().getTime() / 1000;
        token += Long.toHexString(floor);
        token = adjust(token);
        token = Base64.encode(token);
        token = adjust(token);
        return token;
    }

    /**
     * 接口鉴权加密方式
     * 加密字符串默认长度大于2，方法内部不做校验
     * @param str
     * @return
     */
    private static String adjust(String str){
        char[] cs = str.toCharArray();
        int len = cs.length;
        double l = Math.floor((double)len/2);
        int start = (cs[0]+cs[--len])%3;
        for(int i=start;i<l;i++){
            if(cs[i]!=cs[len-i]){
                char tmp = cs[i];
                cs[i] = cs[len-i];
                cs[len-i] = tmp;
                i+=(cs[i]+cs[len-i])%2;
            }
        }
        return String.valueOf(cs);
    }


}
